import axios from "axios";
import { ElLoading } from 'element-plus'
import { ref, nextTick } from "vue";

const loadingInstance = ref(null)
const timer = ref(null)

const request = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '/api' : '',
    timeout: 1000,
    headers: { 'X-Custom-Header': 'foobar' }
});

request.interceptors.request.use(function (config) {

    config.headers.Authorization = 'Bearer ' + localStorage.getItem('accessToken')
    loadingInstance.value = ElLoading.service({ fullscreen: true })

    return config;
}, function (error) {
    return Promise.reject(error);
});

request.interceptors.response.use(async function (response) {
    if (response.data.code !== 200) {
        if (response.data.code === 401) {
            const resp = await refreshToken()
            const accessToken = resp.data.data.accessToken
            localStorage.setItem('accessToken', accessToken)
            response.config.headers.Authorization = 'Bearer ' + accessToken
            return request(response.config)
        } else if (response.data.code === 403) {
            return Promise.reject('无权限')
        } else if (response.data.code === 404) {
            return Promise.reject('获取失败')
        } else if (response.data.code === 500) {
            return Promise.reject('服务端有误')
        }
    }

    timer.value = setTimeout(() => {
        nextTick(() => {
            loadingInstance.value.close()
            clearTimeout(timer.value)
        })
    }, 1000)
    return response;
}, function (error) {
    return Promise.reject(error);
});

const refreshToken = () => {
    return request.get('/refreshToken', { params: { refreshToken: localStorage.getItem('refreshToken') } })
}

export default request